package com.xuyiwei.mayi.test;

import org.junit.Test;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

/**
 * Created by xuyiwei on 2019/4/15.
 * nio直接缓冲区和非直接缓冲区的区别  直接缓冲区避免了在每次调用基础操作系统的一个本机 I/O 操作之前（或之后），虚拟机都会尽量避免将缓冲区的内容复制到中间缓冲区中（或从中间缓冲区中复制内容）
 */
public class DiffentDirect {
    /**
     * 直接缓冲区
     */
    @Test
    public void test01() throws IOException {
        long start = System.currentTimeMillis();

        FileChannel inChannel = FileChannel.open(Paths.get("/Users/xuyiwei/Downloads/mayitest/javaio/src/main/java/com/xuyiwei/mayi/test/NioDemo1.java"), StandardOpenOption.READ);
        FileChannel outChannel = FileChannel.open(Paths.get("/Users/xuyiwei/Downloads/mayitest/javaio/src/main/java/com/xuyiwei/mayi/test/NioDemo2.txt"), StandardOpenOption.READ
                , StandardOpenOption.WRITE,StandardOpenOption.CREATE);
        MappedByteBuffer inMapper = inChannel.map(FileChannel.MapMode.READ_ONLY,0,inChannel.size());
        MappedByteBuffer outMapper = outChannel.map(FileChannel.MapMode.READ_WRITE,0,inChannel.size());
        byte[] dts = new byte[inMapper.limit()];
        inMapper.get(dts);
        outMapper.put(dts);
        inChannel.close();
        outChannel.close();
        long end = System.currentTimeMillis();
        System.out.println(end - start);
    }

    /**
     * 非直接缓冲区
     */
    @Test
    public void test02() throws IOException {
        long start = System.currentTimeMillis();

        FileInputStream in = new FileInputStream(new File("/Users/xuyiwei/Downloads/mayitest/javaio/src/main/java/com/xuyiwei/mayi/test/NioDemo1.java"));
        FileOutputStream out = new FileOutputStream(new File("/Users/xuyiwei/Downloads/mayitest/javaio/src/main/java/com/xuyiwei/mayi/test/NioDemo3.txt"));
        FileChannel inChannel = in.getChannel();
        FileChannel outChannel = out.getChannel();
        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
        while ((inChannel.read(byteBuffer))!=-1){
            //切换到读模式
            byteBuffer.flip();
            outChannel.write(byteBuffer);
            byteBuffer.clear();
        }

        inChannel.close();
        outChannel.close();
        in.close();
        out.close();
        long end = System.currentTimeMillis();
        System.out.println(end - start);
    }
}
